#pragma once
#include "netLib/netExport.h"
#include <functional>
#include <map>
#include <vector>

#include <event2/bufferevent.h>
#include <event2/buffer.h>
#include <event2/listener.h>
#include <event2/util.h>
#include <event2/event.h>

class API_EXPORT NetServer
{
public:
    typedef std::function<void(bufferevent*,char*,int)> RecvFun;
    
public:
    NetServer();
    void setReadCb(RecvFun *pReadCb);
    bool init(int port=1314);
    void loop();
    void disconnect();
    
private:
    void onListen(struct evconnlistener *, 
    evutil_socket_t,struct sockaddr *, int socklen, void *);
    //void onClose(int fd);
    void onRecv(struct bufferevent *bufevt, void *ctx);
    
private:
    friend void readServerCb(bufferevent *bufevt, void *ctx);
    friend void listener_cb(struct evconnlistener *, evutil_socket_t,struct sockaddr *, int socklen, void *);
    friend void conn_writecb(struct bufferevent *, void *);
    friend void conn_eventcb(struct bufferevent *, short, void *);
    friend void signal_cb(evutil_socket_t, short, void *);
    
private:
    struct evconnlistener *m_pListener = nullptr;
    struct event_base* m_pBase;
    std::map<int,bufferevent*> m_connMap;
    std::vector<char> m_recvBuf;
    RecvFun *m_pRecvFun = nullptr;
    static NetServer *pThis;
};